#include "rcc.h"


/* ---------------------- RCC registers bit mask ------------------------ */

/* CR register bit mask */

#define CR_PLL_Mask            ((uint32_t)0xFFFE1FFF) 	
#define CR_PLLMull_Mask        ((uint32_t)0x0001E000)	
#define CR_SWS_Mask              ((uint32_t)0x00000030)
#define CR_SW_Mask               ((uint32_t)0xFFFFFFF3)		
#define CR_HPRE_Reset_Mask       ((uint32_t)0xFFFFFC3F)		
#define CR_HPRE_Set_Mask         ((uint32_t)0x000003C0)		
#define CR_PPRE1_Reset_Mask      ((uint32_t)0xFFFFE3FF)		
#define CR_PPRE1_Set_Mask        ((uint32_t)0x00001C00)		
#define CR_MCO_Reset_Mask     	 ((uint32_t)0xFFF1FFFF)			
#define CR_MCO_Set_Mask       	 ((uint32_t)0x000E0000)			


/* CSR register bit mask */
#define CSR_RMVF_Set              ((uint32_t)0x01000000)

/* RCC Flag Mask */
#define RCC_FLAG_Mask                 ((uint32_t)0x3F)


/**
  * @}
  */ 

/** @defgroup RCC_Private_Macros
  * @{
  */ 

/**
  * @}
  */ 

/** @defgroup RCC_Private_Variables
  * @{
  */ 
static __I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
static __I uint8_t APBAHBPrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9};


/**
  * @}
  */

/** @defgroup RCC_Private_FunctionPrototypes
  * @{
  */

/**
  * @}
  */

/** @defgroup RCC_Private_Functions
  * @{
  */

/**
  * @brief  Resets the RCC clock configuration to the default reset state.
  * @param  None
  * @retval None
  */
void RCC_DeInit(void)
{
  /* Set HSION bit */
  RCC->CR |= (uint32_t)0x00000001;

  /* Reset SW, HPRE, PPRE1, PPRE2, and MCO , PLLON,PLLMUL bits */   
	RCC->CR &= 0xFFF00003;
	
  
  /* Reset LSI, LSE, RTCEN bits */
  RCC->CSR &= 0xFFFFFFF0;

}

ErrorStatus RCC_WaitForHSIStartUp(void)
{
  __IO uint32_t StartUpCounter = 0;
  ErrorStatus status = ERROR;
  FlagStatus HSIStatus = RESET;
  
  /* Wait till HSE is ready and if Time out is reached exit */
  do
  {
    HSIStatus = RCC_GetFlagStatus(RCC_FLAG_HSIRDY);
    StartUpCounter++;  
  } while((StartUpCounter != HSI_STARTUP_TIMEOUT) && (HSIStatus == RESET));
  
  if (RCC_GetFlagStatus(RCC_FLAG_HSIRDY) != RESET)
  {
    status = SUCCESS;
  }
  else
  {
    status = ERROR;
  }  
  return (status);
}
ErrorStatus RCC_WaitForPLLStartUp(void)
{
  __IO uint32_t StartUpCounter = 0;
  ErrorStatus status = ERROR;
  FlagStatus PLLStatus = RESET;
  
  /* Wait till HSE is ready and if Time out is reached exit */
  do
  {
    PLLStatus = RCC_GetFlagStatus(RCC_FLAG_PLLRDY);
    StartUpCounter++;  
  } while((StartUpCounter != HSE_STARTUP_TIMEOUT) && (PLLStatus == RESET));
  
  if (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) != RESET)
  {
    status = SUCCESS;
  }
  else
  {
    status = ERROR;
  }  
  return (status);	
}



ErrorStatus RCC_WaitForLSIStartUp(void)
{
  __IO uint32_t StartUpCounter = 0;
  ErrorStatus status = ERROR;
  FlagStatus PLLStatus = RESET;
  
  /* Wait till HSE is ready and if Time out is reached exit */
  do
  {
    PLLStatus = RCC_GetFlagStatus(RCC_FLAG_LSIRDY);
    StartUpCounter++;  
  } while((StartUpCounter != LSI_STARTUP_TIMEOUT) && (PLLStatus == RESET));
  
  if (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) != RESET)
  {
    status = SUCCESS;
  }
  else
  {
    status = ERROR;
  }  
  return (status);		
}

ErrorStatus RCC_WaitForLSEStartUp(void)
{
  __IO uint32_t StartUpCounter = 0;
  ErrorStatus status = ERROR;
  FlagStatus PLLStatus = RESET;
  
  /* Wait till HSE is ready and if Time out is reached exit */
  do
  {
    PLLStatus = RCC_GetFlagStatus(RCC_FLAG_LSERDY);
    StartUpCounter++;  
  } while((StartUpCounter != LSE_STARTUP_TIMEOUT) && (PLLStatus == RESET));
  
  if (RCC_GetFlagStatus(RCC_FLAG_LSERDY) != RESET)
  {
    status = SUCCESS;
  }
  else
  {
    status = ERROR;
  }  
  return (status);		
}


/**
  * @brief  Enables or disables the Internal High Speed oscillator (HSI).
  * @note   HSI can not be stopped if it is used directly or through the PLL as system clock.
  * @param  NewState: new state of the HSI. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_HSICmd(FunctionalState NewState)
{	
	if (NewState != DISABLE)
  {
    RCC->CR |= RCC_CR_HSION;
  }
  else
  {
    RCC->CR &= ~RCC_CR_HSION;
  }
}

/**
  * @brief  Configures the PLL multiplication factor.
  * @note   This function must be used only when the PLL is disabled.
  *   this parameter can be one of the following values:
  * @param  RCC_PLLMul: specifies the PLL multiplication factor.
  *   For @b this parameter can be RCC_PLLMul_x
  * @retval None
  */
void RCC_PLLConfig(uint32_t RCC_PLLMul)
{
  uint32_t tmpreg = 0;

  tmpreg = RCC->CR;
  /* Clear PLLSRC, PLLXTPRE and PLLMUL[3:0] bits */
  tmpreg &= CR_PLL_Mask;
  /* Set the PLL configuration bits */
  tmpreg |= RCC_PLLMul;
  /* Store the new value */
  RCC->CR = tmpreg;
}

/**
  * @brief  Enables or disables the PLL.
  * @note   The PLL can not be disabled if it is used as system clock.
  * @param  NewState: new state of the PLL. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_PLLCmd(FunctionalState NewState)
{

  if (NewState != DISABLE)
  {
    RCC->CR |= RCC_CR_PLLON;
  }
  else
  {
    RCC->CR &= ~RCC_CR_PLLON;
  }
}

/**
  * @brief  Configures the system clock (SYSCLK).
  * @param  RCC_SYSCLKSource: specifies the clock source used as system clock.
  *   This parameter can be one of the following values:
  *     @arg RCC_SYSCLKSource_HSI: HSI selected as system clock
  *     @arg RCC_SYSCLKSource_PLLCLK: PLL selected as system clock
  * @retval None
  */
void RCC_SYSCLKConfig(uint32_t RCC_SYSCLKSource)
{
  uint32_t tmpreg = 0;

  tmpreg = RCC->CR;
  /* Clear SW[1:0] bits */
  tmpreg &= CR_SW_Mask;
  /* Set SW[1:0] bits according to RCC_SYSCLKSource value */
  tmpreg |= RCC_SYSCLKSource;
  /* Store the new value */
  RCC->CR = tmpreg;
}

/**
  * @brief  Returns the clock source used as system clock.
  * @param  None
  * @retval The clock source used as system clock. The returned value can
  *   be one of the following:
  *     - 0x00: HSI used as system clock
  *     - 0x04: LSI used as system clock
  *     - 0x08: PLL used as system clock
  */
uint8_t RCC_GetSYSCLKSource(void)
{
  return ((uint8_t)(RCC->CR & CR_SWS_Mask));
}

/**
  * @brief  Configures the AHB clock (HCLK).
  * @param  RCC_SYSCLK: defines the AHB clock divider. This clock is derived from 
  *   the system clock (SYSCLK).
  *   This parameter can be one of the following values:
  *     @arg RCC_SYSCLK_Div1: AHB clock = SYSCLK
  *     @arg RCC_SYSCLK_Div2: AHB clock = SYSCLK/2
  *     @arg RCC_SYSCLK_Div4: AHB clock = SYSCLK/4
  *     @arg RCC_SYSCLK_Div8: AHB clock = SYSCLK/8
  *     @arg RCC_SYSCLK_Div16: AHB clock = SYSCLK/16
  *     @arg RCC_SYSCLK_Div64: AHB clock = SYSCLK/64
  *     @arg RCC_SYSCLK_Div128: AHB clock = SYSCLK/128
  *     @arg RCC_SYSCLK_Div256: AHB clock = SYSCLK/256
  *     @arg RCC_SYSCLK_Div512: AHB clock = SYSCLK/512
  * @retval None
  */
void RCC_HCLKConfig(uint32_t RCC_SYSCLK)
{
  uint32_t tmpreg = 0;

  tmpreg = RCC->CR;
  /* Clear HPRE[3:0] bits */
  tmpreg &= CR_HPRE_Reset_Mask;
  /* Set HPRE[3:0] bits according to RCC_SYSCLK value */
  tmpreg |= RCC_SYSCLK;
  /* Store the new value */
  RCC->CR = tmpreg;
}

/**
  * @brief  Configures the Low Speed APB clock (PCLK1).
  * @param  RCC_HCLK: defines the APB1 clock divider. This clock is derived from 
  *   the AHB clock (HCLK).
  *   This parameter can be one of the following values:
  *     @arg RCC_HCLK_Div1: APB1 clock = HCLK
  *     @arg RCC_HCLK_Div2: APB1 clock = HCLK/2
  *     @arg RCC_HCLK_Div4: APB1 clock = HCLK/4
  *     @arg RCC_HCLK_Div8: APB1 clock = HCLK/8
  *     @arg RCC_HCLK_Div16: APB1 clock = HCLK/16
  * @retval None
  */
void RCC_PCLK1Config(uint32_t RCC_HCLK)
{
  uint32_t tmpreg = 0;

  tmpreg = RCC->CR;
  /* Clear PPRE1[2:0] bits */
  tmpreg &= CR_PPRE1_Reset_Mask;
  /* Set PPRE1[2:0] bits according to RCC_HCLK value */
  tmpreg |= RCC_HCLK;
  /* Store the new value */
  RCC->CR = tmpreg;
}


/**
  * @brief  Enables or disables the External Low Speed oscillator (LSE).
  * @note   LSI can not be disabled if the IWDG is running.
  * @param  NewState: new state of the LSI. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_LSECmd(FunctionalState NewState)
{
  if (NewState != DISABLE)
  {
    RCC->CSR |= RCC_CSR_LSEON;
  }
  else
  {
    RCC->CSR &= ~RCC_CSR_LSEON;
  }
}

/**
  * @brief  Enables or disables the Internal Low Speed oscillator (LSI).
  * @note   LSI can not be disabled if the IWDG is running.
  * @param  NewState: new state of the LSI. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_LSICmd(FunctionalState NewState)
{
	
  if (NewState != DISABLE)
  {
    RCC->CSR |= RCC_CSR_LSION;
  }
  else
  {
    RCC->CSR &= ~RCC_CSR_LSION;
  }
}

/**
  * @brief  Enables or disables the DBP.
  * @param  NewState: new state of the LSI. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_DBPCmd(FunctionalState NewState)
{
	
  if (NewState != DISABLE)
  {
    RCC->CSR |= RCC_CSR_DBPON;
  }
  else
  {
    RCC->CSR &= ~RCC_CSR_DBPON;
  }	
}

/**
  * @brief  Configures the RTC clock (RTCCLK).
  * @note   Once the RTC clock is selected it can't be changed unless the Backup domain is reset.
  * @param  RCC_RTCCLKSource: specifies the RTC clock source.
  *   This parameter can be one of the following values:
  *     @arg RCC_RTCCLKSource_LSE: LSE selected as RTC clock
  *     @arg RCC_RTCCLKSource_LSI: LSI selected as RTC clock
  *     @arg 
  * @retval None
  */
void RCC_RTCCLKConfig(uint32_t RCC_RTCCLKSource)
{
  
  uint32_t tmpreg = 0;

	tmpreg = RCC->CSR;
	tmpreg &= ~RCC_RTCCLKSource;	
	tmpreg |= RCC_RTCCLKSource;	

	RCC->CSR = tmpreg;
}

/**
  * @brief  Enables or disables the RTC clock.
  * @note   This function must be used only after the RTC clock was selected using the RCC_RTCCLKConfig function.
  * @param  NewState: new state of the RTC clock. This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_RTCCLKCmd(FunctionalState NewState)
{
  
	if (NewState != DISABLE)
  {
		RCC->CSR |= RCC_RTCEN;
  }
  else
  {

		RCC->CSR &= ~RCC_RTCEN;		
  }
}

/**
  * @brief  Returns the frequencies of different on chip clocks.
  * @param  RCC_Clocks: pointer to a RCC_ClocksTypeDef structure which will hold
  *         the clocks frequencies.
  * @note   The result of this function could be not correct when using 
  *         fractional value for HSE crystal.  
  * @retval None
  */
void RCC_GetClocksFreq(RCC_ClocksTypeDef* RCC_Clocks)
{
  uint32_t tmp = 0, pllmull = 0, presc = 0;

	/********system*********************/
	tmp = RCC->CR & CR_SWS_Mask; // check RCC_CR_SW[3:2]
  switch (tmp)
  {
    case 0x00:  /* HSI used as system clock */
      RCC_Clocks->SYSCLK_Frequency = HSI_VALUE;
      break;
    case 0x10:  /* LSI used as system clock */
      RCC_Clocks->SYSCLK_Frequency = LSI_VALUE;
      break;
    case 0x20:  /* PLL used as system clock */

      /* Get PLL clock source and multiplication factor ----------------------*/
			pllmull = pllmull;
      pllmull = RCC->CR & CR_PLLMull_Mask; //0x0A&0x003C0000 = 0;
//      pllsource = RCC->CR & CFGR_PLLSRC_Mask; //0x0A&0x00010000 = 0;
      
     
      pllmull = ( pllmull >> 13) + 2;
			if(pllmull >16)
				pllmull = 16;
      
			RCC_Clocks->SYSCLK_Frequency = 0;
			RCC_Clocks->SYSCLK_Frequency = (HSI_VALUE >> 1) * pllmull; //16000000/2*2=16000000
			
      break;

    default:
      RCC_Clocks->SYSCLK_Frequency = HSI_VALUE;
      break;
  }	
  /* Compute HCLK, PCLK1 clocks frequencies ----------------*/
  /* Get HCLK prescaler */
  tmp = RCC->CR & CR_HPRE_Set_Mask;  //0x0A&0x000000F0 = 0
  tmp = tmp >> 6;
  presc = AHBPrescTable[tmp];
  /* HCLK clock frequency */
  RCC_Clocks->HCLK_Frequency = RCC_Clocks->SYSCLK_Frequency >> presc;
	
  /* Get PCLK1 prescaler */
  tmp = RCC->CR & CR_PPRE1_Set_Mask;
  tmp = tmp >> 10;
  presc = APBAHBPrescTable[tmp];
  /* PCLK1 clock frequency */
  RCC_Clocks->PCLK1_Frequency = RCC_Clocks->HCLK_Frequency >> presc;

	/********************************************/
}


/**
  * @brief  Enables or disables the Low Speed APB (APB1) peripheral clock.
  * @param  RCC_APB1Periph: specifies the APB1 peripheral to gates its clock.
  *   This parameter can be any combination of the following values:
  *     @arg RCC_APB1Periph_TIM1, RCC_APB1Periph_TIM3, RCC_APB1Periph_TIM14,
  *          RCC_APB1Periph_TIM6, RCC_APB1Periph_TIM7,
  *          RCC_APB1Periph_WWDG, RCC_APB1Periph_SPI2, RCC_APB1Periph_SPI3,
  *          RCC_APB1Periph_UART0, RCC_APB1Periph_UART1, RCC_APB1Periph_UART2, 
  *          RCC_APB1Periph_I2C         
  * @param  NewState: new state of the specified peripheral clock.
  *   This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void  RCC_APB1PeriphClockCmd(uint32_t RCC_APB1Periph, FunctionalState NewState)
{
  
  if (NewState != DISABLE)
  {
    RCC->APB1ENR |= RCC_APB1Periph;
  }
  else
  {
    RCC->APB1ENR &= ~RCC_APB1Periph;
  }
} 



/**
  * @brief  Forces or releases Low Speed APB (APB1) peripheral reset.
  * @param  RCC_APB1Periph: specifies the APB1 peripheral to reset.
  *   This parameter can be any combination of the following values:
  *     @arg RCC_APB1Periph_TIM1, RCC_APB1Periph_TIM3, RCC_APB1Periph_TIM14,
  *          RCC_APB1Periph_TIM6, RCC_APB1Periph_TIM7,
  *          RCC_APB1Periph_WWDG, RCC_APB1Periph_SPI2, RCC_APB1Periph_SPI3,
  *          RCC_APB1Periph_UART0, RCC_APB1Periph_UART1, RCC_APB1Periph_UART2, 
  *          RCC_APB1Periph_I2C   
  * @param  NewState: new state of the specified peripheral clock.
  *   This parameter can be: ENABLE or DISABLE.
  * @retval None
  */
void RCC_APB1PeriphResetCmd(uint32_t RCC_APB1Periph, FunctionalState NewState)
{
  
  if (NewState != DISABLE)
  {
    RCC->APB1RSTR |= RCC_APB1Periph;
  }
  else
  {
    RCC->APB1RSTR &= ~RCC_APB1Periph;
  }
}


/**
  * @brief  Selects the clock source to output on MCO pin.
  * @param  RCC_MCO: specifies the clock source to output.   
  *   For @b this parameter can be one of the
  *   following values:       
  *     @arg RCC_MCO_NoClock: No clock selected
				@arg RCC_MCO_LSI: LSI clock selected
				@arg RCC_MCO_LSE: LSE clock selected
  *     @arg RCC_MCO_SYSCLK: System clock selected						
  *     @arg RCC_MCO_HSI: HSI oscillator clock selected
  *     @arg RCC_MCO_PLLCLK_Div2: PLL clock divided by 2 selected
  *   
  * @retval None
  */
void RCC_MCOConfig(uint32_t RCC_MCO)
{
	uint32_t tmpreg = 0;

	tmpreg	= RCC->CR;
	tmpreg &= CR_MCO_Reset_Mask;
	tmpreg |= RCC_MCO&CR_MCO_Set_Mask;
	RCC->CR = tmpreg;
}

/**
  * @brief  Checks whether the specified RCC flag is set or not.
  * @param  RCC_FLAG: specifies the flag to check.
  *   
  *   this parameter can be one of the
  *   following values:
  *     @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready
  *     @arg RCC_FLAG_PLLRDY: PLL clock ready                          
  *     @arg RCC_FLAG_LSERDY: LSE oscillator clock ready
  *     @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready
  *     @arg RCC_FLAG_PINRST: Pin reset
  *     @arg RCC_FLAG_PORRST: POR/PDR reset
  *     @arg RCC_FLAG_SFTRST: Software reset
  *     @arg RCC_FLAG_IWDGRST: Independent Watchdog reset
  *     @arg RCC_FLAG_WWDGRST: Window Watchdog reset
  *     @arg RCC_FLAG_LPWRRST: Low Power reset   
  * @retval The new state of RCC_FLAG (SET or RESET).
  */
FlagStatus RCC_GetFlagStatus(uint32_t RCC_FLAG)
{
  uint32_t tmp = 0;
  uint32_t statusreg = 0;
  FlagStatus bitstatus = RESET;

  /* Get the RCC register index */
  tmp = RCC_FLAG >> 26;
  if (tmp == 0)               /* The flag to check is in CR register */
  {
    statusreg = RCC->CR;
		tmp = RCC_FLAG & (RCC_FLAG_Mask<<20);
  }
  else                       /* The flag to check is in CSR register */
  {
    statusreg = RCC->CSR;
		tmp = RCC_FLAG & (RCC_FLAG_Mask<<26);
  }

	if ((statusreg & tmp) != (uint32_t)RESET)
  {
    bitstatus = SET;
  }
  else
  {
    bitstatus = RESET;
  }

  /* Return the flag status */
  return bitstatus;
}

/**
  * @brief  Clears the RCC reset flags.
  * @note   The reset flags are: RCC_FLAG_PINRST, RCC_FLAG_PORRST, RCC_FLAG_SFTRST,
  *   RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST, RCC_FLAG_LPWRRST
  * @param  None
  * @retval None
  */
void RCC_ClearFlag(void)
{
  /* Set RMVF bit to clear the reset flags */
  RCC->CSR |= CSR_RMVF_Set;
}
